package com.jike.noobmoney.mvp.view.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.util.MD5;
import com.jike.noobmoney.util.MobileInfoUtil;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.lz.aiwan.littlegame.bean.AdConfig;
import com.lz.aiwan.littlegame.bean.IGamePlayCallback;
import com.lz.aiwan.littlegame.utils.LzLittleGame;

public class GameListActivity extends BaseActivity implements IGamePlayCallback, SwipeRefreshLayout.OnRefreshListener,IView{

    private RelativeLayout mRelativeGameView;
    private SwipeRefreshLayout mPullToRefresh;
    public String userid;

    public TextView tv_title;
    public ImageView iv_back;
    public String deviceno;
    private UserPresenter userPresenter;
    @Override
    protected int layoutResID() {
        return R.layout.activity_game_list;
    }

    @Override
    protected void initData() {
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        userPresenter = new UserPresenter(this);
        tv_title=(TextView)findViewById(R.id.tv_title);
        tv_title.setText("小游戏赚");
        iv_back=(ImageView)findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GameListActivity.this.finish();
            }
        });
        mRelativeGameView = findViewById(R.id.rl_view_gamelist);
        mPullToRefresh = findViewById(R.id.refresh);
        mPullToRefresh.setOnRefreshListener(this);
        initLittle();

        //2.设置监听
        LzLittleGame.getInstance().setGamePlayCallback(this);
        //3.添加游戏(android10.0之前此步会校验imei权限，为了保证添加游戏顺利，最好在添加之前就申请好权限)
        LzLittleGame.getInstance().addGameView(mRelativeGameView,this);
        deviceno= MobileInfoUtil.getIMEI(context);
    }

    /**
     * 打开单个游戏榜单详情页面
     */
    public void openGameSpecialRankDetail(View view) {
        LzLittleGame.getInstance().openGameRankByGid(this, "102");
    }

    /**
     * 打开单个游戏
     */
    public void onButtonClickOpenGameSpecial(View view) {
        //1.打开单个游戏之前，android10.0之前请先确保获取手机设备码权限,否则无法展示游戏
        if (android.os.Build.VERSION.SDK_INT < 29 && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            //没有设备码权限,申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);
            return;
        }

        //2.设置监听
        LzLittleGame.getInstance().setGamePlayCallback(new IGamePlayCallback() {
            @Override
            public void gamePlayTimeCallback(String gameid, String gamename, String gametype, int playTimeInSeconds) {
                //此处回抛游戏试玩状态
                Toast.makeText(GameListActivity.this, "游戏id：" + gameid + "   游戏name: " + gamename + "    游戏类型： " + gametype + "  试玩时间:  " + playTimeInSeconds, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void gameClickCallback(String gameid, String gamename) {
                Toast.makeText(GameListActivity.this, "游戏id：" + gameid + "   游戏name: " + gamename, Toast.LENGTH_SHORT).show();
            }
        });

        //打开单个游戏
        LzLittleGame.getInstance().openGameByGid(this, "102");
    }

    //此处接收设备码权限申请状态，如果前面已经申请成功，此处无需接收
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case LzLittleGame.REQUEST_PHONE_STATE_CODE:
                //权限是否申请成功
                boolean hasPermission = true;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //判断是否勾选禁止后不再询问
                        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
                        hasPermission = false;
                        if (showRequestPermission) {
                            //点了拒绝访问。继续添加游戏模块。模块里面继续申请权限
                            LzLittleGame.getInstance().addGameView(mRelativeGameView,this);
                            return;
                        } else {
                            // false 被禁止了，不在访问,不能激活游戏模块，自行处理
                        }
                    }
                }

                if(hasPermission){
                    //权限申请成功，继续添加游戏模块
                    LzLittleGame.getInstance().addGameView(mRelativeGameView,this);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //通知sdk游戏列表激活
        LzLittleGame.getInstance().onGameListActive(LzLittleGame.GAME_LIST_ONRESUME);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void gamePlayTimeCallback(String gameid, String gamename,String gametype, int time) {
       // Toast.makeText(this,"游戏id："+gameid+"   游戏name: "+gamename+"    游戏类型： "+gametype+"  试玩时间:  "+time,Toast.LENGTH_SHORT).show();
        if(gametype.equals("0")){
            update(userid,deviceno,gameid,gamename,gametype,time);
        }

    }

    /**
     * 游戏时长回调
     */
    private void update(String userid,String deviceno,String  gameid,String gamename,String gametype,Integer time) {
        showProgress();
        String key = "FyzP3scK6d5Q983RiyzHu5tD2eDBlzJr";
        String sign= MD5.GetMD5Code(userid+""+deviceno+""+gameid+""+gamename+""+gametype+""+time+key,true);
        userPresenter.callbackGame(userid,deviceno,gameid,gamename,gametype,time,sign, ConstantValue.RequestKey.game_call_back);
    }

    @Override
    public void gameClickCallback(String gameid, String gamename) {
        //Toast.makeText(this,"游戏id："+gameid+"   游戏name: "+gamename,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRefresh() {
        //下拉刷新通知sdk刷新列表
        LzLittleGame.getInstance().onGameListActive(LzLittleGame.GAME_LIST_ONREFRESH);

        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                mPullToRefresh.setRefreshing(false);
            }
        }, 1500);
    }

    public void initLittle()
    {
        //1.配置参数
        AdConfig adConfig = new AdConfig();
        adConfig.setTtRewardVideo_h_code("945034158");//穿山甲横屏激励视屏广告位id
        adConfig.setTtRewardVideo_v_code("945034310");//穿山甲竖屏激励视频广告位id     928375517
        adConfig.setTtFullVideo_h_code("945034305");//穿山甲横屏全屏视频广告位id
        adConfig.setTtFullVideo_v_code("945034304");//穿山甲竖屏全屏视频广告位id
        adConfig.setTtNativeCode("945034311");//穿山甲插屏广告位id
        adConfig.setTtSplashCode("887296469");////穿山甲开屏广告位id
        adConfig.setTtLoadingNativeCode("945034311");//打开游戏，加载时候的穿山甲插屏广告id、、
        adConfig.setTtGameEndFeedAdId("945034303");//游戏结束确认退出弹框上的穿山甲信息流广告id

        adConfig.setBooleanhideFnishGameDialog(false);//是否隐藏游戏结束时候确认退出dialog。默认不隐藏

        adConfig.setUserid(userid);//必填

        LzLittleGame.getInstance().LaunchLGSDK(this, "1022", "FyzP3scK6d5Q983RiyzHu5tD2eDBlzJr", adConfig);

        LzLittleGame.getInstance().getAdConfig();
        LzLittleGame.getInstance().getAppkey();
        LzLittleGame.getInstance().getAppid();
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.game_call_back.equals(actionType)) {
            ToastUtils.showShortToast("游戏多多，奖励多多");

        }
    }

    @Override
    public void onFailed(String code, String msg) {
        ToastUtils.showShortToast(msg);
        dismissProgress();
    }
}
